local base = _G
module("GUI.EventHandler.Form.PendingOrder")

local os = base.os.getenv("OS")
if os == "Windows_NT" then
	rootdir = ".\\"
else
	rootdir = "\\Program Files\\wmssystem\\"
end

base.print("DBG:Eventhandler GUI.EventHandler.Form.PendingOrder Loaded.\n")

function Parse(methon,para)
	local utils = base.require("Library.Utils.Utils")
	para = utils.Base64_Decode(para)
	base.print("DBG: methon: " .. methon .. " para: " .. para .. "\n")
	if(methon == "back") then
		back()
	else
		--base.print("DBG:Unknown action\n")
		orders(para)
	end
	base.os.exit(0)
end

function orders(para)
	if para == "Unavailable" then
		local utils = base.require("Library.Utils.Utils")
		utils.MessageBox("Unavailable!\n","Warnning",1)
		return 0
	end
	r = base.os.remove(rootdir .. "tmp\\order_detail_tmp.txt")
	
	local file = base.io.open(rootdir .. "\\tmp\\form.txt","w")
	file:write("order_detail")
	--file:write("pendingorder")
	file:close()
	
	local f = base.require("Function.order_management")
	local content = f.Query(para)
	
	
	local h_xmlfile = base.io.open(rootdir .. "XML\\order_detail.xml","rb")
	xmlfile = h_xmlfile:read("*all")
	h_xmlfile:close()
	
	local f_customer = base.require("Function.customer_management")
	local f_stock = base.require("Function.stock_management")
	
	local customer_info = f_customer.Query2(content["CustomerID"])
	
	
	xmlfile = base.string.gsub(xmlfile,"{OrderID}",content["OrderID"] or "Unavailable");
	xmlfile = base.string.gsub(xmlfile,"{Customer}",customer_info["Name"] or "Unavailable");
	xmlfile = base.string.gsub(xmlfile,"{State}",content["State"] or "Unavailable");
	
	local utils = base.require("Library.Utils.Utils")
	local stocks = utils.SplitString(content["StockID"],",")
	local amounts = utils.SplitString(content["Amount"],",")
	
	for i = 1,8,1 do
		local stock_info = f_stock.Query2(stocks[i])
		xmlfile = base.string.gsub(xmlfile,"{Stock" .. i .. "}", stock_info["Name"] or "Unavailable");
		xmlfile = base.string.gsub(xmlfile,"{StockID" .. i .. "}", stock_info["StockID"]);
	end
	
	local h_xmlfile = base.io.open(rootdir .. "XML\\tmp\\order_detail.xml","wb")
	h_xmlfile:write(xmlfile)
	h_xmlfile:close()
	
	return 1
end

function back()
	local file = base.io.open(rootdir .. "\\tmp\\form.txt","w")
	file:write("main")
	file:close()
end